/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unc.pds.news;


import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author ain
 */
public class NewsReciever implements MessageDrivenBean, MessageListener {

    private MessageDrivenContext context;

    // <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click on the + sign on the left to edit the code.">
    /**
     * @see javax.ejb.MessageDrivenBean#setMessageDrivenContext(javax.ejb.MessageDrivenContext)
     */
    public void setMessageDrivenContext(MessageDrivenContext aContext) {
        context = aContext;
    }

    /**
     * See section 15.4.4 of the EJB 2.0 specification
     * See section 15.7.3 of the EJB 2.1 specification
     */
    public void ejbCreate() {
        // TODO Add code to acquire and use other enterprise resources (DataSource, JMS, enterprise bean, Web services)
    }

    /**
     * @see javax.ejb.MessageDrivenBean#ejbRemove()
     */
    public void ejbRemove() {
        // TODO release any resource acquired in ejbCreate.
        // The code here should handle the possibility of not getting invoked
        // See section 15.7.3 of the EJB 2.1 specification
    }

    // </editor-fold>
    public void onMessage(Message aMessage) {
        Message m = (Message) aMessage;
        try {
            Long newsContext = new Long(m.getLongProperty(NewsMessage.CONTEXT_ID_KEY));
            Long entID = new Long(m.getLongProperty(NewsMessage.ENTITY_ID_KEY));
            String event = m.getStringProperty(NewsMessage.EVENT_NAME_KEY);
            Connection conn = null;
            Statement state = null;
            try{
                conn = getConnection();
                state = conn.createStatement();
                state.execute("INSERT INTO NEWS (CONTEXT_ID,EVENT,ENTITY_ID) VALUES ("
                        + newsContext+",'"+event+"',"+entID+")");
            }catch(Exception e){
                e.printStackTrace();
            }
            finally{
                try {
                    if (state!=null) state.close();
                    if (conn!=null) conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (JMSException ex) {
            ex.printStackTrace();
        }
    }
    
    private Connection getConnection() throws NamingException, SQLException {
        DataSource ds = (DataSource) (new InitialContext()).lookup("oracle/SOS");
        return ds.getConnection();
    }
}
